package com.ruoyi.web.controller.expertmodel;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.XssUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.diagmanage.domain.StateInventory;
import com.ruoyi.expertmodel.domain.HealthModel;
import com.ruoyi.expertmodel.domain.PerformanceModel;
import com.ruoyi.expertmodel.domain.PerformanceModel;
import com.ruoyi.expertmodel.service.PerformanceModelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

import static com.ruoyi.common.core.domain.AjaxResult.success;
@Slf4j
@RestController
@RequestMapping("/PerformanceModelController")
public class PerformanceModelController {

    @Resource
    private PerformanceModelService PerformanceModelService;

    public static FileInputStream convertToFileInputStream(InputStream inputStream) throws IOException {
        File tempFile = File.createTempFile("temp", ".tmp");
        tempFile.deleteOnExit();

        try (FileOutputStream outputStream = new FileOutputStream(tempFile)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }

        return new FileInputStream(tempFile);
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.setDisallowedFields(new String[]{"admin"});
    }

    @Log(title = "性能模型查询", businessType = BusinessType.QUERY)
    @PostMapping("/queryPerformanceModel")
    public AjaxResult queryPerformanceModel(@RequestBody PerformanceModel PerformanceModel)
    {
        List<PerformanceModel> PerformanceModels = PerformanceModelService.queryPerformanceModel(PerformanceModel);
        return success(PerformanceModels);
    }

    @Log(title = "性能模型删除", businessType = BusinessType.DELETE)
    @PostMapping("/deletePerformanceModel")
    public AjaxResult deletePerformanceModel(@RequestBody PerformanceModel PerformanceModel)
    {
        boolean b = PerformanceModelService.deletePerformanceModel(PerformanceModel);
        if(b){
            return success("删除成功！");
        }else{
            return success("删除失败！");
        }

    }

    @Log(title = "性能模型插入", businessType = BusinessType.INSERT)
    @PostMapping("/addPerformanceModel")
    public AjaxResult addPerformanceModel(@RequestBody PerformanceModel PerformanceModel)
    {

        boolean b = PerformanceModelService.save(PerformanceModel);
        if(b){
            return success("新增成功！");
        }else{
            return success("新增失败！");
        }

    }

    @Log(title = "性能模型修改", businessType = BusinessType.UPDATE)
    @PostMapping("/updatePerformanceModel")
    public AjaxResult updatePerformanceModel(@RequestBody PerformanceModel PerformanceModel)
    {
        boolean b = PerformanceModelService.updateById(PerformanceModel);
        if(b){
            return success("修改成功！");
        }else{
            return success("修改失败！");
        }

    }

    @PostMapping("/queryPerformanceModelById")
    public AjaxResult queryPerformanceModelById(@RequestBody PerformanceModel PerformanceModel)
    {
        PerformanceModel model = PerformanceModelService.getById(PerformanceModel.getId());
        return success(model);

    }

    @PostMapping("/copyPerformanceModel")
    public AjaxResult copyHealthModel(@RequestBody PerformanceModel PerformanceModel)
    {
        UUID uuid =UUID.randomUUID();
        PerformanceModel.setId(Objects.toString(uuid));
        PerformanceModelService.copyPerformanceModel(PerformanceModel);
        return success("修改成功！");
    }

    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response,PerformanceModel PerformanceModel)
    {
        List<PerformanceModel> PerformanceModels = PerformanceModelService.queryPerformanceModel(PerformanceModel);

        ExcelUtil<PerformanceModel> util = new ExcelUtil<PerformanceModel>(PerformanceModel.class);

        util.exportExcel(response, PerformanceModels, "性能模型");
    }

    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        String c= file.getOriginalFilename();
        int index = c.lastIndexOf(".");
        String suffix = c.substring(index + 1);
        String contentType = file.getContentType();
        if (!"xlsx".equals(suffix) && !"xls".equals(suffix)) {
            return AjaxResult.error("仅允许上传excel文件");
        }
        //
        ExcelUtil<PerformanceModel> util = new ExcelUtil<PerformanceModel>(PerformanceModel.class);
        //测，xssf对象xlsx
        // hssf 对应都可以  这里 xls
        InputStream is = null;
        InputStream is2 = null;
        FileInputStream fileInputStream = null;
        try {

            is = file.getInputStream();
            is2 = file.getInputStream();
            fileInputStream = convertToFileInputStream(is);
            boolean t = false;
            if("xlsx".equals(suffix)){
                t = XssUtil.checkXSSFExcelXssFlag(fileInputStream);
            }else if("xls".equals(suffix)){
                t = XssUtil.checkXSSFExcelXssFlag(fileInputStream);
            }

            if(t){
                List<PerformanceModel> PerformanceList = util.importExcel(is2);
                boolean flag = PerformanceModelService.batchImport(PerformanceList);

                if(flag){
                    return success("成功");
                }else{
                    return success("失敗");
                }
            }

        }catch (Exception e){
            log.info(e.toString());
        } finally {

            if(is !=null ){
                try{
                    is.close();
                }catch (Exception e){
                    log.info(e.toString());
                }


            }
            if(fileInputStream !=null ){
                try{
                    fileInputStream.close();
                }catch (Exception e){
                    log.info(e.toString());
                }


            }
            if(is2 !=null ){
                try{
                    is2.close();
                }catch (Exception e){
                    log.info(e.toString());
                }

            }

        }
        return AjaxResult.error("失败");
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<PerformanceModel> util = new ExcelUtil<PerformanceModel>(PerformanceModel.class);
        util.importTemplateExcel(response, "性能模型");
    }





}
